
/*
 * @Description: ServerSocket 服务端
 * @Author: rendc
 * @Date: 2025-08-25 11:06:05
 * @LastEditors: rendc
 * @LastEditTime: 2025-08-25 11:40:42
 */
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServerSocket {
  // 创建服务器端对象
  public static void main(String[] args) throws Exception {
    // Server 等待客户端连接
    int port = 8888;
    ServerSocket server = new ServerSocket(port);
    System.out.println("服务端：启动成功，等待客户端连接，端口：" + port);
    System.out.println("server:" + server);
    // 获取客户端连接对象 终端会阻塞 等待客户端连接
    Socket socket = server.accept();
    System.out.println("服务端：客户端连接成功：" + socket);
    // 获取IO流
    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();
    // 获取客户端的信息
    byte[] buff = new byte[1024];
    int length = is.read(buff);
    System.out.println(new String(buff, 0, length));
    System.out.println("服务端：成功接收到客户端的消息");
    // 给客户端发消息
    os.write("hello client,I'm server".getBytes());
    System.out.println("服务端：成功发送消息");
    // 关闭流
    os.close();
    is.close();
    // 关闭连接对象
    socket.close();
    server.close();
  }
}